// MySQL データベース名、ユーザ名、パスワード
var DB_NAME = "test";
var DB_USER = "app_user";
var DB_PASSWD = "app";

// モジュールの読み込み
var sys = require("sys"),
    Client = require("mysql").Client;

// MySQLデータベースに接続しcallbackを呼び出す
function mysql(callback) {
    var client = new Client();
    client.database = DB_NAME;
    client.user = DB_USER;
    client.password = DB_PASSWD;

    client.connect(function(err) {
        if (err) {
            throw err;
        }
        callback(client);
    });
}

// mysql 実行
    mysql(function(client) {
        client.query(
            "SELECT user_id, message, CONVERT_TZ(registered, '+09:00', '+00:00') registered FROM chat_history",
            function(err, results, fields) {
                if (err) {
                    client.end();
                    throw err;
                }
                if (results.length == 0) {
                    client.end();
                    throw new Error("data is nothing");
                }
                client.end();

                var now = new Date();
                for (var i = 0; i < results.length; i ++) {
                    // 今日の日付の場合は時間のみ表示
                    var dt = new Date(results[i].registered);
                    var dt_str = null;
                    if (now.getYear() + now.getMonth() + now.getDate() == dt.getYear() + dt.getMonth() + dt.getDate()) {
                        dt_str = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
                    }
                    else {
                        dt_str = (dt.getYear() + 1900) + "-" + (dt.getMonth() + 1) + "-" + dt.getDate() + " " 
                        + dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
                    }

                    console.log(results[i].user_id + ":" + results[i].message + " " + dt_str);
                }
             }
         );
    });

